package io.renren.modules.oa.task;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

import io.renren.common.utils.DateUtils;
import io.renren.common.utils.dingtalk.DingtalkUtils;
import io.renren.modules.oa.entity.OaPlanConfigEntity;
import io.renren.modules.oa.entity.OaPlanEmployeeEntity;
import io.renren.modules.oa.entity.OaPlanLogEntity;
import io.renren.modules.oa.entity.UserConfigEntity;
import io.renren.modules.oa.redis.DingtalkRedis;
import io.renren.modules.oa.service.OaPlanConfigService;
import io.renren.modules.oa.service.OaPlanEmployeeService;
import io.renren.modules.oa.service.OaPlanLogService;
import io.renren.modules.oa.websocket.DingtalkSocket;

/**
 * 钉钉考勤打卡请假定时器
 * 
 * @author Administrator
 *
 */
@Component("dingtalkTask")
public class DingtalkTask {
	private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private OaPlanConfigService oaPlanConfigService;
	
	@Autowired
	private OaPlanLogService oaPlanLogService;

	@Autowired
	private OaPlanEmployeeService oaPlanEmployeeService;

	/*************************************
	 * 钉钉打卡请假 start
	 *******************************************/
	/**
	 * 钉钉考勤(打卡)
	 * 
	 * @param params
	 */
	public void attendance(String params) {
		try {
			// 0 1 2 3 4 5 6
			// 0,1 2,3 4,5 6,0 1,2
			Thread.sleep(1000L);
			// 查询所有配置列表
			List<OaPlanConfigEntity> list = DingtalkRedis.queryPlanConfigList();
			for (OaPlanConfigEntity planConfig : list) {
				boolean run = false;
				Long merchantId = planConfig.getMerchantId();
				UserConfigEntity config = DingtalkRedis.getUserConfig(merchantId);
				if (config != null && StringUtils.isNotEmpty(config.getDingAppkey())
						&& StringUtils.isNotEmpty(config.getDingAppsecret())) {
					List<OaPlanEmployeeEntity> employeeList = DingtalkRedis.queryAllList(merchantId);
					// 组装未打卡用户集合
					List<String> userids = Lists.newArrayList();
					for (OaPlanEmployeeEntity oaPlanEmployeeEntity : employeeList) {
						if (!DingtalkRedis.isActive(oaPlanEmployeeEntity.getUserid())) {
							userids.add(oaPlanEmployeeEntity.getUserid());
						}
					}
					if (userids != null && userids.size() > 0) {
						JSONArray attendanceList = DingtalkRedis
								.attendanceList(DingtalkRedis.getAccessToken(merchantId), userids);
						// 添加打开记录
						if (attendanceList != null) {
							for (int i = 0; i < attendanceList.length(); i++) {
								JSONObject attendance = attendanceList.getJSONObject(i);
								if (insertOaPlanLogEntity(attendance, planConfig)) {
									run = true;
								}
							}
							System.out.println(attendanceList);
						}
					}
					if (run) {
						DingtalkSocket.sendAllUser(planConfig.getMerchantId(),
								DingtalkRedis.getAdInfo(planConfig.getMerchantId()));
						
						
					}
					
				} else {
					logger.info("用户ID(" + config.getMerchantId() + ")未开通钉钉打卡功能");
				}
			}
			// 1.查询所有用户userids
			// 2.根据userids查询所有打卡记录

			// 3.去掉已打开userids
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	// 插入打开记录
	private boolean insertOaPlanLogEntity(JSONObject attendance, OaPlanConfigEntity planConfig) {
		boolean runsocket = false;
		String userid = attendance.getString("userId");
		// 考勤类型 OnDuty：上班 OffDuty：下班
		String checkType = attendance.getString("checkType");
		// 时间结果 Normal：正常; Early：早退; Late：迟到; SeriousLate：严重迟到；
		String timeResult = attendance.getString("timeResult");
		if (/* checkType.equals("OnDuty") && */ !timeResult.equals("NotSigned")) {
			if (!DingtalkRedis.isActive(userid)) { // 打卡记录
				OaPlanLogEntity planLog = oaPlanLogService.selectByUserid(userid, "1", DateUtils.getStartTime(),
						DateUtils.getEndTime());
				if (planLog == null) {
					OaPlanEmployeeEntity planEmployee = oaPlanEmployeeService.selectByUserid(planConfig.getMerchantId(),
							userid);

					planLog = new OaPlanLogEntity();
					planLog.setMerchantId(planConfig.getMerchantId());
					planLog.setTitle(planConfig.getTitle());
					planLog.setName(planEmployee.getName());
					planLog.setAvatar(planEmployee.getAvatar());
					planLog.setType("1");
					planLog.setUserid(userid);

					Long userCheckTime = attendance.getLong("userCheckTime");
					planLog.setCreateTime(
							DateUtils.timeStamp2Date(userCheckTime.toString(), DateUtils.DATE_TIME_PATTERN));
					oaPlanLogService.insert(planLog);

					//
					JSONObject msg = new JSONObject();
					msg.put("name", planEmployee.getName());
					msg.put("planEmployee", planEmployee.getAvatar());

					runsocket = true;
				}
				DingtalkRedis.setActive(userid, DateUtils.format(new Date()));
				System.out.println("userid:" + userid + "打卡成功");
			}
		}
		return runsocket;
	}
	
	
	
	/**
	 * 初始化值班系统
	 * @param planConfigId
	 */
	public void initZhiBanList(String params) {
		try {
			Thread.sleep(1000L);
			// 查询所有配置列表
			Date today = new Date();
			List<OaPlanConfigEntity> list = DingtalkRedis.queryPlanConfigList();
			for (OaPlanConfigEntity planConfig : list) {
				planConfig = oaPlanConfigService.selectById(planConfig.getId());  //查询计划配置
				if (planConfig.getPlanDate() != null && today.getTime() > planConfig.getPlanDate().getTime()) {
					List<OaPlanEmployeeEntity> activeList = DingtalkRedis.queryActiveList(planConfig.getMerchantId());  
					
					List<OaPlanLogEntity> lastZhiBanList = oaPlanLogService.queryLastZhiBanList(planConfig.getMerchantId(),planConfig.getCount());
					if(lastZhiBanList != null && lastZhiBanList.size() > 0){
						for (OaPlanLogEntity planLog : lastZhiBanList) {
							if(planLog.getCreateTime().getTime() > DateUtils.getStartTime().getTime()){  //今日已值日
								System.out.println("今日已值日");
							}else{
								//System.out.println("");
								int days = planConfig.getDays();  //值日天数
								//1 < 2   2 < 2
								if(planLog.getDays() < days){
									planLog.setCreateTime(DateUtils.addDateMinutes(DateUtils.getStartTime(), 480));
									planLog.setDays(planLog.getDays() + 1);
									oaPlanLogService.insert(planLog);
								}else{
									OaPlanEmployeeEntity planEmployee = getPlanLogByUserid(activeList, planLog.getUserid(), planConfig.getCount());
									planLog = new OaPlanLogEntity();
									planLog.setMerchantId(planConfig.getMerchantId());
									planLog.setTitle(planConfig.getTitle());
									planLog.setName(planEmployee.getName());
									planLog.setAvatar(planEmployee.getAvatar());
									planLog.setType("3");	
									planLog.setUserid(planEmployee.getUserid());
									planLog.setCreateTime(DateUtils.addDateMinutes(DateUtils.getStartTime(), 480));
									planLog.setDays(1);
									oaPlanLogService.insert(planLog);
								}
							}
						}
						System.out.println("值班定时器");
					}else{	//初始化 值班系统
						System.out.println("初始化今日值班数据");
						for (int i = 0; i < planConfig.getCount(); i++) {
		    				OaPlanEmployeeEntity planEmployee = activeList.get(i);
		    				OaPlanLogEntity planLog = planLog = new OaPlanLogEntity();
							planLog.setMerchantId(planConfig.getMerchantId());
							planLog.setTitle(planConfig.getTitle());
							planLog.setName(planEmployee.getName());
							planLog.setAvatar(planEmployee.getAvatar());
							planLog.setType("3");	
							planLog.setUserid(planEmployee.getUserid());
							planLog.setCreateTime(DateUtils.addDateMinutes(DateUtils.getStartTime(), 480));
							planLog.setDays(1);
							oaPlanLogService.insert(planLog);
		    			}
					}
					System.out.println(lastZhiBanList);

				} else {
					System.out.println("值班系统未启动");
				}
			}
			
			// 1.查询所有用户userids
			// 2.根据userids查询所有打卡记录

			// 3.去掉已打开userids
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/************************************** 钉钉打卡请假 end *******************************************/

	/************************************** 值班系统 start *******************************************/
	public void zhiban(String params) {
		try {
			Thread.sleep(1000L);
			StringBuffer userids = new StringBuffer();
			StringBuffer names = new StringBuffer();
			// 查询所有配置列表
			Date today = new Date();
			List<OaPlanConfigEntity> list = DingtalkRedis.queryPlanConfigList(); // 1541217458900
																					// 1541174400000
			
			for (OaPlanConfigEntity planConfig : list) {
				planConfig = oaPlanConfigService.selectById(planConfig.getId());  //查询计划配置
				if (planConfig.getPlanDate() != null && today.getTime() > planConfig.getPlanDate().getTime()) {
					List<OaPlanEmployeeEntity> activeList = DingtalkRedis.queryActiveList(planConfig.getMerchantId());  
					
					List<OaPlanLogEntity> lastZhiBanList = oaPlanLogService.queryLastZhiBanList(planConfig.getMerchantId(),planConfig.getCount());
					if(lastZhiBanList != null && lastZhiBanList.size() > 0){
						
						for (int i = 0; i < lastZhiBanList.size(); i++) {
							OaPlanLogEntity planLog = lastZhiBanList.get(i);
							
							//1  2   3   4  5
							//System.out.println("");
							int days = planConfig.getDays();  //值日天数
							//1   2  
							if(planLog.getDays() < days){
								String zifu = (i > 0) ? ",":"";
								names.append(zifu).append(planLog.getName());
								if(planLog.getDays() < days){
									userids.append(zifu).append(planLog.getUserid());
								}else{
									OaPlanEmployeeEntity e = getPlanLogByUserid(activeList, planLog.getUserid(), planConfig.getCount());
									userids.append(zifu).append(e.getUserid());
								}
							}else{	
								//第一天、第二天都是同一个人
								String zifu = (i > 0) ? ",":"";
			    				names.append(zifu).append(planLog.getName());
			    				if(planLog.getDays() < days){
									userids.append(zifu).append(planLog.getUserid());
								}else{
									OaPlanEmployeeEntity e = getPlanLogByUserid(activeList, planLog.getUserid(), planConfig.getCount());
									userids.append(zifu).append(e.getUserid());
								}
							}
						}
						if(names.length() > 0 && userids.length() > 0){
							planConfig.setPlanJson(names.toString());
							oaPlanConfigService.insertOrUpdate(planConfig);
							System.out.println("值班定时器");
						}
					}
					System.out.println(lastZhiBanList);

				} else {
					System.out.println("值班系统未启动");
				}
				//大于16点
				if((today.getTime() - DateUtils.getStartTime().getTime()) > 1000 * 60 * 60 * 16){
					List<OaPlanLogEntity> dakalist = oaPlanLogService.selectList("1", DateUtils.getStartTime(), DateUtils.getEndTime());
					if(dakalist.size() > 0){
						//发送钉钉通知
						if(names.length() > 0 && userids.length() > 0){
							String text = "";
							if(DateUtils.isSaturday(today)){
								text = "下周一("+DateUtils.format(DateUtils.addDateDays(new Date(), 2))+"),该你做值日了！";
							}else{
								text = "明天("+DateUtils.format(DateUtils.addDateDays(new Date(), 1))+"),该你做值日了！";
							}
							DingtalkUtils.sendText(DingtalkRedis.getAccessToken(planConfig.getMerchantId()), names.toString(), userids.toString(), text);
							System.out.println("值班定时器");
						}
					}else{
						oaPlanLogService.delList("3", DateUtils.getStartTime());
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	//根据每日人数、用户唯一标识取明日值班人员
	private OaPlanEmployeeEntity getPlanLogByUserid(List<OaPlanEmployeeEntity> planEmployeeList,String userid,Integer count){
		int index = 0;
		int len = planEmployeeList.size();
		// 1   2   3  4  5     2
		// 0   1   2  3  4    
		for (int i = 0; i < len; i++) {
			OaPlanEmployeeEntity entity = planEmployeeList.get(i);
			if(entity.getUserid().equals(userid)){
				if((i + count) < len ){
					index = i + count;  //默认第一个
				}else{
					index = (i + count - len);
				}
				break;
			}
		}
		return planEmployeeList.get(index);
	}
	
	private String getPlanJson(String userids,String names,String indexs,Integer count,Integer status){
		JSONObject plan = new JSONObject();
		plan.put("today", userids);
		plan.put("name", names);
		plan.put("index", indexs);
		plan.put("count", count);
		plan.put("status", status);
		return plan.toString();
	}
	
	
	
	
	/************************************** 值班系统 end *******************************************/

}
